<template>
  <div>
    <!-- 面包屑 -->
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">巡检管理</span>
    </div>

    <!-- 标题与操作 -->
    <div class="flex items-center justify-between mb-6">
      <div>
      <h1 class="text-2xl font-bold text-gray-900">巡检管理</h1>
        <p class="text-gray-600 mt-1">管理巡检计划、任务分配和执行进度</p>
      </div>
      <div class="flex space-x-3">
        <button 
          @click="handleAddPlan"
          class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-plus"></i>
          <span>新增计划</span>
        </button>
        <button 
          @click="handleAddTask"
          class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-tasks"></i>
          <span>新增任务</span>
        </button>
        <button 
          v-if="selectedTasks.length > 0"
          @click="handleBatchDelete"
          class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-trash"></i>
          <span>批量删除 ({{ selectedTasks.length }})</span>
        </button>
        <button 
          @click="handleExport"
          class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-file-export"></i>
          <span>导出数据</span>
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总任务数</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.totalTasks }}</p>
          </div>
          <div class="bg-blue-100 p-3 rounded-lg">
            <i class="fas fa-tasks text-blue-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">进行中</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.inProgress }}</p>
          </div>
          <div class="bg-yellow-100 p-3 rounded-lg">
            <i class="fas fa-clock text-yellow-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">已完成</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.completed }}</p>
          </div>
          <div class="bg-green-100 p-3 rounded-lg">
            <i class="fas fa-check-circle text-green-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">超时</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.timeout }}</p>
          </div>
          <div class="bg-red-100 p-3 rounded-lg">
            <i class="fas fa-exclamation-triangle text-red-600 text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <div class="relative">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            <input 
              v-model="searchForm.keyword"
              type="text" 
              placeholder="搜索计划/任务..." 
              class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @keyup.enter="handleSearch"
            >
          </div>
          <select 
            v-model="searchForm.status"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            @change="handleSearch"
          >
            <option value="">全部状态</option>
            <option v-for="option in statusOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <select 
            v-model="searchForm.cycle"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            @change="handleSearch"
          >
            <option value="">全部周期</option>
            <option v-for="option in cycleOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <button 
            @click="handleSearch"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            <i class="fas fa-search mr-1"></i>搜索
          </button>
          <button 
            @click="handleReset"
            class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition-colors"
          >
            <i class="fas fa-undo mr-1"></i>重置
          </button>
        </div>
        <div class="flex items-center space-x-2">
          <button 
            @click="handleRefresh"
            class="text-blue-600 hover:text-blue-800 flex items-center space-x-1"
          >
            <i class="fas fa-sync-alt"></i>
            <span>刷新</span>
          </button>
          <div class="flex items-center space-x-2 text-sm text-gray-500">
          <span>展示：</span>
            <button 
              @click="handleViewModeChange('plan')"
              :class="[
                'px-3 py-1 rounded border border-gray-300',
                viewMode === 'plan' ? 'bg-blue-600 text-white' : 'bg-white hover:bg-gray-50'
              ]"
            >
              计划
            </button>
            <button 
              @click="handleViewModeChange('task')"
              :class="[
                'px-3 py-1 rounded border border-gray-300',
                viewMode === 'task' ? 'bg-blue-600 text-white' : 'bg-white hover:bg-gray-50'
              ]"
            >
              任务
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表区域 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
      <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-900">{{ viewMode === 'plan' ? '计划列表' : '任务列表' }}</h3>
        <div v-if="loading" class="text-sm text-gray-500">
          <i class="fas fa-spinner fa-spin mr-1"></i>加载中...
        </div>
        <div v-else class="text-sm text-gray-500">
          共 {{ pagination.total }} 条
        </div>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300"
                  :checked="selectAll"
                  @change="handleSelectAll($event.target.checked)"
                >
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {{ viewMode === 'plan' ? '计划编号' : '任务编号' }}
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {{ viewMode === 'plan' ? '计划名称' : '计划名称' }}
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {{ viewMode === 'plan' ? '巡检路线' : '巡检路线' }}
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {{ viewMode === 'plan' ? '负责人' : '负责人' }}
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">周期</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {{ viewMode === 'plan' ? '创建时间' : '截止时间' }}
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in displayList" :key="item.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300"
                  :checked="selectedTasks.includes(item.id)"
                  @change="handleSelect($event.target.checked, item)"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ item.code }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.lineName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.assignee }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ cycleText[item.cycle] }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(item.status)" class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                  {{ statusText[item.status] }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.deadline || item.createTime }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center space-x-2">
                  <button 
                    @click="handleView(item)"
                    class="text-blue-600 hover:text-blue-800"
                    title="查看详情"
                  >
                    <i class="fas fa-eye"></i>
                  </button>
                  <button 
                    @click="handleEdit(item)"
                    class="text-green-600 hover:text-green-800"
                    title="编辑"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                  <button 
                    v-if="viewMode === 'task' && item.status === 'pending'"
                    @click="handleAssign(item)"
                    class="text-purple-600 hover:text-purple-800"
                    title="分配任务"
                  >
                    <i class="fas fa-user-plus"></i>
                  </button>
                  <button 
                    @click="handleDelete(item)"
                    class="text-red-600 hover:text-red-800"
                    title="删除"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
            <tr v-if="displayList.length === 0 && !loading">
              <td :colspan="9" class="px-6 py-8 text-center text-gray-500">
                <i class="fas fa-inbox text-4xl mb-2"></i>
                <p>暂无数据</p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示 {{ (pagination.pageNum - 1) * pagination.pageSize + 1 }}-{{ Math.min(pagination.pageNum * pagination.pageSize, pagination.total) }} 条，共 {{ pagination.total }} 条记录
          </div>
          <div class="flex items-center space-x-2">
            <button 
              @click="handlePageChange(pagination.pageNum - 1)"
              :disabled="pagination.pageNum <= 1"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <button 
              v-for="page in Math.ceil(pagination.total / pagination.pageSize)"
              :key="page"
              @click="handlePageChange(page)"
              :class="[
                'px-3 py-1 text-sm rounded',
                page === pagination.pageNum 
                  ? 'bg-blue-600 text-white' 
                  : 'border border-gray-300 hover:bg-gray-50'
              ]"
            >
              {{ page }}
            </button>
            <button 
              @click="handlePageChange(pagination.pageNum + 1)"
              :disabled="pagination.pageNum >= Math.ceil(pagination.total / pagination.pageSize)"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑/查看弹窗 -->
    <div v-if="dialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">{{ dialogTitle }}</h3>
          <button 
            @click="dialogVisible = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <form @submit.prevent="handleSave" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">
                  {{ dialogTitle.includes('计划') ? '计划名称' : '任务名称' }} *
                </label>
                <input 
                  v-if="dialogTitle.includes('计划')"
                  v-model="formData.name"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入计划名称"
                >
                <input 
                  v-else
                  v-model="taskFormData.name"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入任务名称"
                >
              </div>
              <div v-if="dialogTitle.includes('任务')">
                <label class="block text-sm font-medium text-gray-700 mb-1">关联计划</label>
                <select 
                  v-model="taskFormData.planId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择关联计划（可选）</option>
                  <option v-for="plan in planOptions" :key="plan.id" :value="plan.id">
                    {{ plan.name }}
                  </option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">巡检路线 *</label>
                <select 
                  v-if="dialogTitle.includes('计划')"
                  v-model="formData.lineId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检路线</option>
                  <option v-for="line in lineOptions" :key="line.id" :value="line.id">
                    {{ line.name }}
                  </option>
                </select>
                <select 
                  v-else
                  v-model="taskFormData.lineId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检路线</option>
                  <option v-for="line in lineOptions" :key="line.id" :value="line.id">
                    {{ line.name }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div v-if="dialogTitle.includes('计划') || (dialogTitle.includes('任务') && dialogMode === 'edit')">
                <label class="block text-sm font-medium text-gray-700 mb-1">负责人 *</label>
                <select 
                  v-if="dialogTitle.includes('计划')"
                  v-model="formData.assigneeId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择负责人</option>
                  <option v-for="user in userOptions" :key="user.id" :value="user.id">
                    {{ user.name }}
                  </option>
                </select>
                <select 
                  v-else
                  v-model="taskFormData.assigneeId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择负责人</option>
                  <option v-for="user in userOptions" :key="user.id" :value="user.id">
                    {{ user.name }}
                  </option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">巡检周期 *</label>
                <select 
                  v-if="dialogTitle.includes('计划')"
                  v-model="formData.cycle"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检周期</option>
                  <option v-for="option in cycleOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
                <select 
                  v-else
                  v-model="taskFormData.cycle"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检周期</option>
                  <option v-for="option in cycleOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div v-if="dialogTitle.includes('计划') || (dialogTitle.includes('任务') && dialogMode === 'edit')">
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select 
                  v-if="dialogTitle.includes('计划')"
                  v-model="formData.status"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option v-for="option in planStatusOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
                <select 
                  v-else
                  v-model="taskFormData.status"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option v-for="option in taskStatusOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
              <div v-if="dialogTitle.includes('任务')">
                <label class="block text-sm font-medium text-gray-700 mb-1">截止时间</label>
                <input 
                  v-model="taskFormData.deadline"
                  type="datetime-local"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
              </div>
              <div v-if="dialogMode === 'view' && dialogTitle.includes('计划')">
                <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                <input 
                  v-model="formData.createTime"
                  type="text"
                  disabled
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                >
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">
                {{ dialogTitle.includes('计划') ? '描述' : '备注' }}
              </label>
              <textarea 
                v-if="dialogTitle.includes('计划')"
                v-model="formData.description"
                :disabled="dialogMode === 'view'"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入计划描述"
              ></textarea>
              <textarea 
                v-else
                v-model="taskFormData.remark"
                :disabled="dialogMode === 'view'"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入任务备注"
              ></textarea>
            </div>
          </form>
        </div>
        
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button 
            @click="dialogVisible = false"
            class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
          <button 
            v-if="dialogMode !== 'view'"
            @click="handleSave"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            {{ dialogMode === 'add' ? '新增' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 任务分配弹窗 -->
    <div v-if="assignDialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">分配任务</h3>
          <button 
            @click="assignDialogVisible = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">任务信息</label>
              <div class="p-3 bg-gray-50 rounded-lg">
                <p class="text-sm font-medium">{{ assignForm.taskName }}</p>
                <p class="text-xs text-gray-500">{{ assignForm.lineName }}</p>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">分配给 *</label>
              <select 
                v-model="assignForm.assigneeId"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">请选择负责人</option>
                <option v-for="user in userOptions" :key="user.id" :value="user.id">
                  {{ user.name }}
                </option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">截止时间 *</label>
              <input 
                v-model="assignForm.deadline"
                type="datetime-local"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
              <textarea 
                v-model="assignForm.remark"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入分配备注"
              ></textarea>
            </div>
          </div>
        </div>
        
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button 
            @click="assignDialogVisible = false"
            class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
          <button 
            @click="handleAssignSave"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            分配
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { inspectionAPI, lineAPI } from '@/api/modules'

/**
 * 响应式数据
 */
// 列表数据
const planList = ref([])
const taskList = ref([])
const loading = ref(false)
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: '',
  cycle: ''
})

// 视图模式
const viewMode = ref('task') // plan, task

// 统计卡片数据
const statistics = ref({
  totalTasks: 0,
  inProgress: 0,
  completed: 0,
  timeout: 0
})

// 选中的任务
const selectedTasks = ref([])
const selectAll = ref(false)

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view

// 分配弹窗状态
const assignDialogVisible = ref(false)

// 表单数据
const formData = ref({
  id: null,
  name: '',
  lineId: '',
  assigneeId: '',
  cycle: '',
  status: 'active',
  description: '',
  createTime: ''
})

// 分配表单数据
const assignForm = ref({
  taskId: null,
  taskName: '',
  lineName: '',
  assigneeId: '',
  deadline: '',
  remark: ''
})

// 任务表单数据
const taskFormData = ref({
  id: null,
  name: '',
  planId: '',
  lineId: '',
  assigneeId: '',
  cycle: '',
  status: 'pending',
  deadline: '',
  startTime: '',
  completionTime: '',
  remark: '',
  progress: 0
})

// 选项数据
// 巡检计划状态选项（只有启用和禁用）
const planStatusOptions = [
  { label: '启用', value: 'active' },
  { label: '禁用', value: 'disabled' }
]

// 巡检任务状态选项
const taskStatusOptions = [
  { label: '待分配', value: 'pending' },
  { label: '进行中', value: 'in_progress' },
  { label: '待回执', value: 'pending_receipt' },
  { label: '已完成', value: 'completed' },
  { label: '超时', value: 'timeout' },
  { label: '已停用', value: 'disabled' }
]

const cycleOptions = [
  { label: '日', value: 'daily' },
  { label: '周', value: 'weekly' },
  { label: '月', value: 'monthly' },
  { label: '自定义', value: 'custom' }
]

const lineOptions = ref([])

const userOptions = ref([])

const planOptions = ref([])

/**
 * 计算属性
 */
// 根据当前视图模式返回状态选项
const statusOptions = computed(() => {
  return viewMode.value === 'plan' ? planStatusOptions : taskStatusOptions
})

// 计划状态文本映射
const planStatusText = computed(() => {
  const statusMap = {
    active: '启用',
    disabled: '禁用'
  }
  return statusMap
})

// 任务状态文本映射
const taskStatusText = computed(() => {
  const statusMap = {
    pending: '待分配',
    in_progress: '进行中',
    pending_receipt: '待回执',
    completed: '已完成',
    timeout: '超时',
    disabled: '已停用'
  }
  return statusMap
})

// 通用状态文本映射（兼容旧代码）
const statusText = computed(() => {
  return { ...planStatusText.value, ...taskStatusText.value }
})

const cycleText = computed(() => {
  const cycleMap = {
    daily: '日',
    weekly: '周',
    monthly: '月',
    custom: '自定义'
  }
  return cycleMap
})

const displayList = computed(() => {
  return viewMode.value === 'plan' ? planList.value : taskList.value
})

/**
 * 模拟数据
 */
// 示例数据已移除，所有数据都从后端API获取

// 示例数据已移除，所有数据都从后端API获取

/**
 * 加载线路选项
 */
const loadLineOptions = async () => {
  try {
    const response = await lineAPI.getLines({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      lineOptions.value = (response.data.records || []).map(item => ({
        id: item.id,
        name: item.lineName || item.name
      }))
    }
  } catch (error) {
    console.error('加载线路选项失败:', error)
  }
}

/**
 * 加载用户选项
 */
const loadUserOptions = async () => {
  try {
    // 从巡检任务数据中提取用户信息
    const response = await inspectionAPI.getTasks({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      const users = new Map()
      const tasks = response.data.records || []
      
      // 提取所有用户信息
      tasks.forEach(task => {
        if (task.assigneeId && task.assigneeName) {
          users.set(task.assigneeId, {
            id: task.assigneeId,
            name: task.assigneeName
          })
        }
      })
      
      userOptions.value = Array.from(users.values())
    }
  } catch (error) {
    console.error('加载用户选项失败:', error)
  }
}

/**
 * 加载计划选项
 */
const loadPlanOptions = async () => {
  try {
    const response = await inspectionAPI.getPlans({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      planOptions.value = (response.data.records || []).map(item => ({
        id: item.id,
        name: item.name
      }))
    }
  } catch (error) {
    console.error('加载计划选项失败:', error)
  }
}

/**
 * 获取计划列表
 */
const loadPlanList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.value.keyword || undefined,
      status: searchForm.value.status || undefined,
      cycle: searchForm.value.cycle || undefined
    }
    
    const response = await inspectionAPI.getPlans(params)
    
    if (response.code === 0) {
      const data = response.data
      // 映射字段名，将后端返回的字段映射到前端使用的字段
      planList.value = (data.records || []).map(item => ({
        ...item,
        assignee: item.assigneeName,    // 将assigneeName映射到assignee
        assigneeId: item.assigneeId,     // 将assigneeId映射到assigneeId
        createTime: item.createdAt,     // 将createdAt映射到createTime
        lineName: item.lineName         // 直接使用后端返回的lineName
      }))
      
      // 更新分页信息
      pagination.value.total = data.total || 0
      pagination.value.pages = data.pages || 0
    } else {
      throw new Error(response.message || '获取巡检计划列表失败')
    }
    
  } catch (error) {
    console.error('加载计划列表失败:', error)
    ElMessage.error('加载计划列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取任务列表
 */
const loadTaskList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.value.keyword || undefined,
      status: searchForm.value.status || undefined,
      cycle: searchForm.value.cycle || undefined
    }
    
    const response = await inspectionAPI.getTasks(params)
    
    if (response.code === 0) {
      const data = response.data
      // 映射字段名，将后端返回的字段映射到前端使用的字段
      taskList.value = (data.records || []).map(item => ({
        ...item,
        assignee: item.assigneeName,    // 将assigneeName映射到assignee
        assigneeId: item.assigneeId,     // 将assigneeId映射到assigneeId
        createTime: item.createdAt,     // 将createdAt映射到createTime
        lineName: item.lineName         // 直接使用后端返回的lineName
      }))
      
      // 更新分页信息
      pagination.value.total = data.total || 0
      pagination.value.pages = data.pages || 0
      
      // 更新统计数据
      updateStatistics()
    } else {
      throw new Error(response.message || '获取巡检任务列表失败')
    }
    
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 更新统计数据
 */
const updateStatistics = async () => {
  try {
    const response = await inspectionAPI.getTaskStatistics()
    
    if (response.code === 0) {
      const data = response.data
      statistics.value = {
        totalTasks: data.totalTasks || 0,
        inProgress: data.inProgress || 0,
        completed: data.completed || 0,
        timeout: data.timeout || 0
      }
    } else {
      console.error('获取任务统计失败:', response.message)
    }
  } catch (error) {
    console.error('获取任务统计失败:', error)
  }
}

/**
 * 加载数据
 */
const loadData = () => {
  if (viewMode.value === 'plan') {
    loadPlanList()
  } else {
    loadTaskList()
  }
}

/**
 * 搜索功能
 */
const handleSearch = () => {
  pagination.value.pageNum = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    status: '',
    cycle: ''
  }
  pagination.value.pageNum = 1
  loadData()
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  loadData()
}

/**
 * 分页处理
 */
const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadData()
}

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked) => {
  selectAll.value = checked
  if (checked) {
    selectedTasks.value = displayList.value.map(item => item.id)
  } else {
    selectedTasks.value = []
  }
}

/**
 * 单个选择
 */
const handleSelect = (checked, item) => {
  if (checked) {
    selectedTasks.value.push(item.id)
  } else {
    const index = selectedTasks.value.indexOf(item.id)
    if (index > -1) {
      selectedTasks.value.splice(index, 1)
    }
  }
  
  // 更新全选状态
  selectAll.value = selectedTasks.value.length === displayList.value.length
}

/**
 * 新增计划
 */
const handleAddPlan = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增计划'
  formData.value = {
    id: null,
    name: '',
    lineId: '',
    assigneeId: '',
    cycle: '',
    status: 'active',
    description: '',
    createTime: ''
  }
  dialogVisible.value = true
}

/**
 * 新增任务
 */
const handleAddTask = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增任务'
  taskFormData.value = {
    id: null,
    name: '',
    planId: '',
    lineId: '',
    assigneeId: '',
    cycle: '',
    status: 'pending',
    deadline: '',
    startTime: '',
    completionTime: '',
    remark: '',
    progress: 0
  }
  dialogVisible.value = true
}

/**
 * 编辑
 */
const handleEdit = (item) => {
  dialogMode.value = 'edit'
  dialogTitle.value = viewMode.value === 'plan' ? '编辑计划' : '编辑任务'
  
  if (viewMode.value === 'plan') {
    // 编辑计划
    formData.value = { 
      ...item,
      assignee: item.assigneeName,    // 将assigneeName映射到assignee
      assigneeId: item.assigneeId,     // 将assigneeId映射到assigneeId
      createTime: item.createdAt,     // 将createdAt映射到createTime
      lineName: item.lineName         // 直接使用后端返回的lineName
    }
  } else {
    // 编辑任务
    taskFormData.value = {
      ...item,
      planId: item.planId || '',
      lineId: item.lineId || '',
      assigneeId: item.assigneeId || '',
      cycle: item.cycle || '',
      status: item.status || 'pending',
      deadline: item.deadline || '',
      startTime: item.startTime || '',
      completionTime: item.completionTime || '',
      remark: item.remark || '',
      progress: item.progress || 0
    }
  }
  
  dialogVisible.value = true
}

/**
 * 查看详情
 */
const handleView = (item) => {
  dialogMode.value = 'view'
  dialogTitle.value = viewMode.value === 'plan' ? '计划详情' : '任务详情'
  formData.value = { 
    ...item,
    assignee: item.assigneeName,    // 将assigneeName映射到assignee
    assigneeId: item.assigneeId,     // 将assigneeId映射到assigneeId
    createTime: item.createdAt,     // 将createdAt映射到createTime
    lineName: item.lineName         // 直接使用后端返回的lineName
  }
  dialogVisible.value = true
}

/**
 * 删除
 */
const handleDelete = async (item) => {
  try {
    const itemType = viewMode.value === 'plan' ? '计划' : '任务'
    await ElMessageBox.confirm(
      `确定要删除${itemType}"${item.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    let response
    if (viewMode.value === 'plan') {
      // 删除计划
      response = await inspectionAPI.deletePlan(item.id)
    } else {
      // 删除任务
      response = await inspectionAPI.deleteTask(item.id)
    }
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      throw new Error(response.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }

  try {
    const itemType = viewMode.value === 'plan' ? '计划' : '任务'
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTasks.value.length} 个${itemType}吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const loadingMessage = ElMessage({
      message: `正在删除${itemType}...`,
      type: 'info',
      duration: 0
    })

    try {
      let successCount = 0
      let failCount = 0
      const errors = []

      // 并发删除所有选中的项目
      const deletePromises = selectedTasks.value.map(async (id) => {
        try {
          let response
          if (viewMode.value === 'plan') {
            response = await inspectionAPI.deletePlan(id)
          } else {
            response = await inspectionAPI.deleteTask(id)
          }
          
          if (response.code === 0) {
            successCount++
          } else {
            failCount++
            errors.push(`ID ${id}: ${response.message || '删除失败'}`)
          }
        } catch (error) {
          failCount++
          errors.push(`ID ${id}: ${error.message || '删除失败'}`)
        }
      })

      await Promise.all(deletePromises)
      loadingMessage.close()

      // 显示结果
      if (failCount === 0) {
        ElMessage.success(`批量删除成功，共删除 ${successCount} 个${itemType}`)
      } else if (successCount === 0) {
        ElMessage.error(`批量删除失败，${failCount} 个${itemType}删除失败`)
        console.error('批量删除错误详情:', errors)
      } else {
        ElMessage.warning(`批量删除完成，成功 ${successCount} 个，失败 ${failCount} 个`)
        console.error('部分删除失败详情:', errors)
      }

      // 清空选择并刷新数据
      selectedTasks.value = []
      selectAll.value = false
      loadData()
    } catch (deleteError) {
      loadingMessage.close()
      throw deleteError
    }

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

/**
 * 分配任务
 */
const handleAssign = (item) => {
  assignForm.value = {
    taskId: item.id,
    taskName: item.name,
    lineName: item.lineName,
    assigneeId: '',
    deadline: '',
    remark: ''
  }
  assignDialogVisible.value = true
}


/**
 * 保存
 */
const handleSave = async () => {
  try {
    // 判断是计划还是任务
    const isPlan = dialogTitle.value.includes('计划')
    const currentFormData = isPlan ? formData.value : taskFormData.value
    
    // 表单验证
    if (!currentFormData.name.trim()) {
      ElMessage.warning(`请输入${isPlan ? '计划' : '任务'}名称`)
      return
    }
    if (!currentFormData.lineId) {
      ElMessage.warning('请选择巡检路线')
      return
    }
    if (!currentFormData.cycle) {
      ElMessage.warning('请选择巡检周期')
      return
    }
    
    let response
    if (isPlan) {
      // 计划验证
      if (!currentFormData.assigneeId) {
        ElMessage.warning('请选择负责人')
        return
      }
      
      // 构建计划请求数据
      const requestData = {
        name: currentFormData.name.trim(),
        lineId: parseInt(currentFormData.lineId),
        assigneeId: parseInt(currentFormData.assigneeId),
        cycle: currentFormData.cycle,
        status: currentFormData.status || 'active',
        description: currentFormData.description || ''
      }
      
      if (dialogMode.value === 'add') {
        response = await inspectionAPI.createPlan(requestData)
      } else {
        response = await inspectionAPI.updatePlan(currentFormData.id, requestData)
      }
    } else {
      // 构建任务请求数据
      const requestData = {
        name: currentFormData.name.trim(),
        planId: currentFormData.planId ? parseInt(currentFormData.planId) : null,
        lineId: parseInt(currentFormData.lineId),
        assigneeId: currentFormData.assigneeId ? parseInt(currentFormData.assigneeId) : null,
        cycle: currentFormData.cycle,
        status: currentFormData.status || 'pending',
        deadline: currentFormData.deadline || null,
        startTime: currentFormData.startTime || null,
        completionTime: currentFormData.completionTime || null,
        remark: currentFormData.remark || '',
        progress: currentFormData.progress || 0
      }
      
      if (dialogMode.value === 'add') {
        response = await inspectionAPI.createTask(requestData)
      } else {
        response = await inspectionAPI.updateTask(currentFormData.id, requestData)
      }
    }
    
    if (response.code === 0) {
      ElMessage.success(dialogMode.value === 'add' ? 
        `新增${isPlan ? '计划' : '任务'}成功` : '编辑成功')
      dialogVisible.value = false
      loadData()
    } else {
      throw new Error(response.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  }
}

/**
 * 保存分配
 */
const handleAssignSave = async () => {
  try {
    // 表单验证
    if (!assignForm.value.assigneeId) {
      ElMessage.warning('请选择负责人')
      return
    }
    if (!assignForm.value.deadline) {
      ElMessage.warning('请选择截止时间')
      return
    }
    
    // 构建分配请求数据
    const assignData = {
      assigneeId: parseInt(assignForm.value.assigneeId),
      deadline: assignForm.value.deadline,
      remark: assignForm.value.remark || ''
    }
    
    // 调用分配API
    const response = await inspectionAPI.assignTask(assignForm.value.taskId, assignData)
    
    if (response.code === 0) {
      ElMessage.success('任务分配成功')
      assignDialogVisible.value = false
      loadData()
    } else {
      throw new Error(response.message || '分配失败')
    }
    
  } catch (error) {
    console.error('分配失败:', error)
    ElMessage.error(error.message || '分配失败')
  }
}

/**
 * 导出数据
 */
const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据...')
    
    // 模拟导出API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  const classes = {
    // 计划状态样式
    active: 'bg-green-100 text-green-800',
    disabled: 'bg-gray-100 text-gray-800',
    // 任务状态样式
    pending: 'bg-yellow-100 text-yellow-800',
    in_progress: 'bg-blue-100 text-blue-800',
    pending_receipt: 'bg-orange-100 text-orange-800',
    completed: 'bg-green-100 text-green-800',
    timeout: 'bg-red-100 text-red-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

/**
 * 监听视图模式变化
 */
const handleViewModeChange = (mode) => {
  viewMode.value = mode
  selectedTasks.value = []
  selectAll.value = false
  pagination.value.pageNum = 1
  loadData()
}

/**
 * 组件挂载时加载数据
 */
onMounted(() => {
  loadData()
  loadLineOptions()
  loadUserOptions()
  loadPlanOptions()
})
</script>

<style scoped>
.toolbar { margin-bottom: 12px; display: flex; gap: 8px; }
.card { background: #fff; border: 1px solid #eee; padding: 16px; border-radius: 6px; }
</style>
